<template>
  <!-- 上传组件 -->
  <el-upload
    action="#"
    v-model="fileList"
    :limit="1"
    list-type="picture-card"
    :auto-upload="false"
    :on-change="handleChange"
    :on-exceed="handleExceed"
    :on-remove="handleRemove"
    :file-list="fileList"
    :class="{ hide: fileList.length >= 1 }"
  >
    <div class="iconfont icon-plus text-4xl text-gray-500"></div>
  </el-upload>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { nanoid } from "nanoid";

const fileList = defineModel({
  default: () => [],
});

// 文件变化处理
const handleChange = (file) => {
  const isImage = file.raw.type.startsWith("image/");
  const isLt5M = file.raw.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB!");
    return false;
  }

  let fileItem = {
    id: nanoid(),
    name: file.name,
    url: file.url,
  };

  fileList.value = [fileItem];
};

// 删除图片方法
const handleRemove = (file) => {
  fileList.value = fileList.value.filter((item) => item.url !== file.url);
  ElMessage.success("图片已删除");
};

// 处理超出文件限制
const handleExceed = () => {
  ElMessage.warning("只能上传一张图片");
  innerFileList.value = [];
};
</script>

<style lang="scss">
/* 隐藏上传按钮的样式 */
.hide .el-upload--picture-card {
  display: none !important;
}
</style>
